from enum import Enum
from typing import Optional

from fastapi import FastAPI, Query
from pydantic import BaseModel

app = FastAPI()


# uvicorn fast_api_test:app --reload
# http://127.0.0.1:8000/docs
# http://127.0.0.1:8000/redoc

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None


@app.get("/")
async def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    """
    :param item_id: 路径参数
    :param q: 查询参数(由于q有默认值，请求时可以不发送该参数)
    :return:
    """
    return {"item_id": item_id, "q": q}


@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}


class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"


@app.get("/model/{model_name}")
async def get_model(model_name: ModelName):
    """
    枚举的使用
    :param model_name:
    :return:
    """
    if model_name == ModelName.alexnet:
        return {"model_name": model_name, "message": "Deep Learning FTW!"}
    if model_name.value == "lenet":
        return {"model_name": model_name, "message": "LeCNN all the images"}
    return {"model_name": model_name, "message": "Have some residuals"}


@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
    """
    :param file_path:  /home/johndoe/myfile.txt
    :return:
    """
    return {"file_path": file_path}


@app.get("/items/{item_id}")
async def read_user_item(item_id: str, limit: Optional[int] = None):
    """
    :param item_id: 您可以Optional用来告诉mypy该值可能是None
    :param limit:
    :return:
    """
    item = {"item_id": item_id, "limit": limit}
    return item


@app.post("/items/create_item")
async def create_item(item: Item):
    return item


@app.get("/items/read_items")
async def read_items(
        q: str = Query(
            None,
            alias="item-query",
            title="Query string",
            description="Query string for the items to search in the database that have a good match",
            min_length=3,
            max_length=50,
            regex="^fixedquery$",
            deprecated=True,
        )
):
    results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
    if q:
        results.update({"q": q})
    return results
